import React, { AnchorHTMLAttributes, ButtonHTMLAttributes, MouseEventHandler, ReactNode, FC } from 'react'
import classNames from 'classnames'
import { SizeType } from '@/types'

const PRE_CLS = 'tyc-btn'

export type ButtonType = 'primary' | 'default' | 'danger' | 'link'

export interface BaseButtonProps {
  /** 设置 Button 的类型 */
  type?: ButtonType
  /** 设置 Button 的尺寸 */
  size?: SizeType
  /** 设置 Button 的禁用 */
  disabled?: boolean
  /** 设置 link 类型 Button 的链接 */
  href?: string
  children?: ReactNode;
  onClick?: MouseEventHandler<HTMLElement>
}

type NativeButtonProps = BaseButtonProps & Omit<ButtonHTMLAttributes<HTMLElement>, 'type' | 'onClick'>
type AnchorButtonProps = BaseButtonProps & Omit<AnchorHTMLAttributes<HTMLElement>, 'type' | 'onClick'>
export type ButtonProps = Partial<NativeButtonProps & AnchorButtonProps>
/**
 * 页面中最常用的的按钮元素，适合于完成特定的交互
 * ### 引用方法
 *
 * ~~~js
 * import { Button } from 'xxx'
 * ~~~
 *
 * @param type 设置 Button 的类型
 * @param size 设置 Button 的尺寸
 * @param disabled 设置 Button 的禁用
 * @param href 设置 link 类型 Button 的链接
 */
const Button: FC<ButtonProps> = props => {
  const { type, size, disabled, href, children, className, ...restProps } = props
  const classes = classNames(PRE_CLS, className, {
    [`${PRE_CLS}-${type}`]: type,
    [`${PRE_CLS}-${size}`]: size,
    disabled: (type === 'link') && disabled
  })
  if (type === 'link' && href) return <a className={classes} href={href} {...restProps}>{children}</a>
  return (
    <button className={classes} disabled={disabled} {...restProps}>
      {children}
    </button>
  )
}

Button.defaultProps = {
  disabled: false,
  type: 'default'
}

export default Button
